package cn.acewill.yxd.yunxundian.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.model.viewReportBean;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.user.ImageViewPagerActivity;

/**
 * Created by XXX on 2017/9/11.
 */

public class MyLookEvaluationRecycleAdatper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //item类型
    public static final int ITEM_TYPE_HEADER = 0;
    public static final int ITEM_TYPE_CONTENT = 1;
    public static final int ITEM_TYPE_BOTTOM = 2;
    private int mHeaderCount=1;//头部View个数
    private int mBottomCount=1;//底部View个数
    private static Context context;
    ArrayList<viewReportBean> list;
    private List<viewReportBean.ZhutiBean> zhutiList;
    public static List<String>myImgList;
    private ImgGradeAdapter ImgAdapter;;

   public MyLookEvaluationRecycleAdatper(Context context, ArrayList<viewReportBean> list){
        this.context =context;
        this.list = list;
        this.zhutiList=list.get(0).getZhuti();

    }
    //判断当前item是否是headview
    public boolean isheadview(int position){
        return mHeaderCount!=0 && position<mHeaderCount;
    }
    //body的长度
    public int getContentItemCount(){
        return zhutiList==null?0:zhutiList.size();
    }
    //判断是否是footview
    public boolean isfootView(int position){
        return mBottomCount!=0&&position>=(mHeaderCount+getContentItemCount());
    }

    //设置不同的view
    @Override
    public int getItemViewType(int position) {
        int dataItemCount = getContentItemCount();
        if (mHeaderCount != 0 && position < mHeaderCount) {
            //头部View
            return ITEM_TYPE_HEADER;
        } else if (mBottomCount != 0 && position >= (mHeaderCount + dataItemCount)) {
            //底部View
            return ITEM_TYPE_BOTTOM;
        } else {
            //内容View  itemView = LayoutInflater.from(context).inflate(R.layout.look_evaluation_header,parent,false);
            return ITEM_TYPE_CONTENT;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView=null;
        if (viewType==ITEM_TYPE_HEADER){

            return new HeadViewHolder(itemView);
        }
        if (viewType==ITEM_TYPE_CONTENT){
            itemView=LayoutInflater.from(context).inflate(R.layout.evadetail_item_view,parent,false);
            return new ContentViewHolder(itemView);
        }
        if (viewType==ITEM_TYPE_BOTTOM){
            itemView = LayoutInflater.from(context).inflate(R.layout.look_evaluation_foot,parent,false);
            return new footViewHolder(itemView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        //设置显示的数据源
        if (holder instanceof HeadViewHolder){
            List<viewReportBean.JibenxinxiBean> jlist = list.get(0).getJibenxinxi();
            for (viewReportBean.JibenxinxiBean bean :jlist){

                ((HeadViewHolder) holder).titleName.setText(bean.getReportname());
                /**
                 *  日期格式转换
                 *  在职能选项中，日程可能未结束
                 *
                 */
                if (bean.getRealend()!=null){
                    String date=bean.getRealend().replace("T"," ");
                    ((HeadViewHolder) holder).taskCompleteData.setText(date.substring(0,10));
                }else{
                    ((HeadViewHolder) holder).taskCompleteData.setText("尚未完成");
                }

              ((HeadViewHolder) holder).taskOperator.setText(bean.getEmpname());
                ((HeadViewHolder) holder).taskArea.setText(bean.getAreaname());
                ((HeadViewHolder) holder).shopName.setText(bean.getShopname());
                ((HeadViewHolder) holder).deductMark.setText("----");
                ((HeadViewHolder) holder).thisEvaScore.setText(bean.getSlevel()+bean.getSscore());
            }

        }//boday
        else if (holder instanceof ContentViewHolder){

            viewReportBean.ZhutiBean rr = zhutiList.get(position-1);
            ((ContentViewHolder) holder).majorName.setText(rr.getDaxiangming());
            ((ContentViewHolder) holder).minorItemName.setText(rr.getXiaoxiangbianhao()+rr.getXiaoxiangming());
            ((ContentViewHolder) holder).taskScore.setText("得分："+rr.getXuanzexiang()+"(满分："+rr.getXiaoxiangmanfen()+")");
            //描述是否存在
            if (rr.getXiaoxiangmiaoshu()!=null&&!TextUtils.isEmpty(rr.getXiaoxiangmiaoshu())){
                ((ContentViewHolder) holder).desc.setVisibility(View.VISIBLE);
                ((ContentViewHolder) holder).taskDesc.setText("描述："+rr.getXiaoxiangmiaoshu());
            }else{
                ((ContentViewHolder) holder).desc.setVisibility(View.GONE);
            }
            if (rr.getShifenxiangfujian()!=null&&!TextUtils.isEmpty(rr.getShifenxiangfujian().toString())){
                final List<String>Jpglist=new ArrayList<>();
                List<String> thisVideoList=new ArrayList<>();
                String[] file =rr.getShifenxiangfujian().toString().replace("[","").replace("]","").split(",");
                for (int i=0;i<file.length;i++){
                    if (file[i].endsWith(".jpg")){
//                    tempFile=tempFile.substring(tempFile.lastIndexOf("/",tempFile.length()));
                        Jpglist.add(pubClass.downLoadUri+file[i].trim());

                    }else if (file[i].endsWith(".mp4")){
                        thisVideoList.add(pubClass.downLoadUri+file[i].trim());
                    }
                }
                //判断是否存在照片
                if (Jpglist==null||Jpglist.size()==0){
                    ((ContentViewHolder) holder).photoLinear.setVisibility(View.GONE);
                }else{
                    ((ContentViewHolder) holder).photoLinear.setVisibility(View.VISIBLE);
                    myImgList = new ArrayList<>();
                    for (int k=0;k<Jpglist.size();k++){
                        myImgList.add(Jpglist.get(k));
                    }
                    List<String> result=new ArrayList<>();
                    for (String s:myImgList){
                        if (Collections.frequency(result,s)<1){
                            result.add(s);
                        }
                    }
                    myImgList.clear();
                    myImgList=result;
                    ImgAdapter=new ImgGradeAdapter(context,Jpglist);
                    ((ContentViewHolder) holder).pictureList.setAdapter(ImgAdapter);
                    ((ContentViewHolder) holder).pictureList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            int i= Jpglist.size();
                            //循环生成一个String
                            String jpsStr="";
                            for (int k=0;k<Jpglist.size();k++){
                                jpsStr+=Jpglist.get(k).toString()+",";
                            }
                            // TODO: 2017/7/6 可以加上判断是否存在本地图片，此处没有加判断
//                        Rect rect = new Rect();
//                        view.getGlobalVisibleRect(rect);
//                        Log.e("viewsize",rect.toString());
                            //加入当前的view的视图位置
                            context.startActivity(new Intent(context, ImageViewPagerActivity.class)
                                    .putExtra("filepath",jpsStr).putExtra("position",position));

//                        String fileName= (String) parent.getItemAtPosition(position);
//                        //拼接路径
//                        BaseActivity.showToast(context,position+"");
//                        String[] thisname=fileName.split("\\/");
//                        String savepath=path+thisname[thisname.length-1];
//                        //判断是否存在问价
//                        File myfile=new File(savepath);
//                        if (!myfile.exists()){
//                            downloadFile(fileName,savepath,1);
//                        }else{
//                            //直接打开文件
//                            context.startActivity(new Intent(context,ImgDetailActivity.class).putExtra("filepath",savepath));
//                        }
                        }
                    });
                }

                if (thisVideoList.size()==0){
                    ((ContentViewHolder) holder).videoLinear.setVisibility(View.GONE);
                }else {
                        ((ContentViewHolder) holder).videoLinear.setVisibility(View.VISIBLE);

                    String path = thisVideoList.get(0);
                    String palyUrl;
                    String[] name=path.split("\\/");
                    String savePath=pubClass.videoSavePath+name[name.length-1];
//                    if (((ContentViewHolder) holder).NcVideo.performClick()){
//                        Log.e("performClick","重新点击下");
//                    }
                    File files = new File(savePath);
                    if (files.exists()){
                        palyUrl = savePath;
                    }else{
                        downloadFile(path,savePath);
                        palyUrl=path;
                    }
                    ((ContentViewHolder) holder).NcVideo.setPlayerType(NiceVideoPlayer.TYPE_IJK);
                    ((ContentViewHolder) holder).NcVideo.setUp(palyUrl,null);
                    TxVideoPlayerController controller = new TxVideoPlayerController(context);
                    String[] thisname=name[name.length-1].split("\\_");
                    if (thisname.length>=3){
                        controller.setTitle(thisname[2]+thisname[3]);
                    }else{
                        controller.setTitle("");
                    }
                    //   controller.setTitle(name);
                    ((ContentViewHolder) holder).NcVideo.setController(controller);
                    ((ContentViewHolder) holder).NcVideo.setBackgroundColor(Color.BLACK);
                }
            }
            else {
                ((ContentViewHolder) holder).photoLinear.setVisibility(View.GONE);
                ((ContentViewHolder) holder).videoLinear.setVisibility(View.GONE);
            }
        }//foot
        else if (holder instanceof footViewHolder){

            String qianming=list.get(0).getQianming();
            if (!TextUtils.isEmpty(qianming)){
                ((footViewHolder) holder).shopSignLinear.setVisibility(View.VISIBLE);
                final String singPath= pubClass.downLoadUri+qianming;
                Glide.with(context).load(singPath).thumbnail(0.1f)
                        .into(((footViewHolder) holder).signCon);
                ((footViewHolder) holder).shopSignLinear.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        context.startActivity(new Intent(context, ImageViewPagerActivity.class).putExtra("filepath", singPath));
                    }
                });
            }else{
                //无签名则隐藏
                ((footViewHolder) holder).shopSignLinear.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public int getItemCount() {

        return mHeaderCount+getContentItemCount()+mBottomCount;
    }

    public static class ContentViewHolder extends RecyclerView.ViewHolder{
        TextView majorName;
        TextView minorItemName;
        TextView taskDesc;
        TextView taskScore;
        GridView pictureList;
        LinearLayout desc;
        LinearLayout videoLinear;
        LinearLayout photoLinear;
        NiceVideoPlayer NcVideo;
        public ContentViewHolder(View itemView) {
            super(itemView);
            majorName= (TextView) itemView.findViewById(R.id.majorName);
            minorItemName= (TextView) itemView.findViewById(R.id.minorItemName);
            taskDesc= (TextView) itemView.findViewById(R.id.taskDesc);
            taskScore= (TextView) itemView.findViewById(R.id.taskScore);
            pictureList= (GridView) itemView.findViewById(R.id.pictureList);
            desc= (LinearLayout) itemView.findViewById(R.id.desc);
            videoLinear= (LinearLayout) itemView.findViewById(R.id.videoLinear);
            photoLinear= (LinearLayout) itemView.findViewById(R.id.photoLinear);
            NcVideo= (NiceVideoPlayer) itemView.findViewById(R.id.NcVideo);

        }

    }


    public static class HeadViewHolder extends RecyclerView.ViewHolder{
        TextView titleName;
        TextView taskCompleteData;
        TextView taskOperator;
        TextView taskArea;
        TextView shopName;
        TextView deductMark;
        TextView thisEvaScore;
        public HeadViewHolder(View itemView) {
            super(itemView);
            titleName= (TextView) itemView.findViewById(R.id.titleName);
            taskCompleteData= (TextView) itemView.findViewById(R.id.taskCompleteData);
            taskArea= (TextView) itemView.findViewById(R.id.taskArea);
            taskOperator= (TextView) itemView.findViewById(R.id.taskOperator);
            shopName= (TextView) itemView.findViewById(R.id.shopName);
            deductMark= (TextView) itemView.findViewById(R.id.deductMark);
            thisEvaScore= (TextView) itemView.findViewById(R.id.thisEvaScore);
        }
    }
    public static class footViewHolder extends RecyclerView.ViewHolder{
        ImageView signCon;
        LinearLayout shopSignLinear;
        public footViewHolder(View itemView) {
            super(itemView);
            signCon= (ImageView) itemView.findViewById(R.id.signCon);
            shopSignLinear= (LinearLayout) itemView.findViewById(R.id.shopSignLinear);
        }
    }

    public static void downloadFile(final String url, String path) {

        String requestUrl="";
        final RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        if (requestUrl==url){
            return;
        }
        requestUrl=url;
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }
            @Override
            public void onStarted() {

            }
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
//                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//                progressDialog.setMessage("努力加载中....");
//                progressDialog.show();
//                progressDialog.setProgress((int)current);
//                progressDialog.setMax((int) total);
//                float all=(float) Math.round(total*1000)/1024/1024/1000;
               float percent=(float) Math.round(current*1000)/1024/1024/1000;
//                progressDialog.setProgressNumberFormat(String.format("%.3fM/%.3fM",percent,all));
                Log.e("progress",percent+"M");
            }
            @Override
            public void onSuccess(File result) {
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
        //        BaseActivity.showAnimaDialog(context,"视频获取失败，请检查网络与存储权限或路径已失效");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }

}
